//
//  ZZCMeController.m
//  ZZC-Finance
//
//  Created by mac on 2017/5/21.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "ZZCMeController.h"
#import "ZZCMeHeadView.h"
#import "ZZCMeCell.h"
#import "ZZCMe.h"
#import "ZZCLoginController.h"
#import "ZZCJoinController.h"
#import "ZZCPropertyController.h"
#import "ZZCOwnPropertyController.h"
#import "ZZCTwoDimensionalController.h"
#import "ZZCTransactionRecordController.h"
#import "ZZCNeedAssetsController.h"
#import "ZZCCollectController.h"
#import "ZZCRecordController.h"
#import "ZZCSetUpController.h"
#import "ZZCMyOrderController.h"
#import "ZZCMyLabourController.h"


#import "ZZCMeInfo.h"
static NSString *meCell = @"meCell";

@interface ZZCMeController ()<UITableViewDelegate,UITableViewDataSource>
@property (strong, nonatomic) UITableView *meTableView;
@property (strong, nonatomic) NSMutableArray *meArray;
@property (strong, nonatomic) NSArray *meData;
@property (assign, nonatomic) BOOL isLogin;//判断是否登录
@property (strong, nonatomic) ZZCMeInfo *meInfoModel;

@property (strong, nonatomic) ZZCLoginController *loginVC;
@property (copy,   nonatomic) NSString *WARN;

@end

@implementation ZZCMeController

-(void)viewWillAppear:(BOOL)animated {
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"isLogin"]) {
        [self reloadSucceedData];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHex:0xeeeeee];
    self.title = @"我的";
    [self.view addSubview:self.meTableView];
    [self initMeData];
    //监听登录成功的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadSucceedData) name:@"loginSucceed" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadSucceedData) name:@"updetaMeInfo" object:nil];
    //退出登录的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadLeaveData) name:@"loginLeave" object:nil];
}

//初始化数据
- (void)initMeData {
    self.meData = @[@"我的订单",@"我的资产",@"劳务合作",@"交易记录",@"需求资产",@"二维码",@"设置"];
}
//登录成功后刷新数据源
- (void)reloadSucceedData {
    self.isLogin = YES;
    
    NSString *token = ZZCNSUserDefaults(@"token");
    NSDictionary *dict = @{@"token":token};
    NSString *sign = [ZZCRequest getSignWithDict:dict];
    sign = [NSString md5:[sign lowercaseString]];
    NSDictionary *param = @{@"timestamp":[NSString timeStr],@"sign":sign,@"token":token};
    [[ZZCRequest sharedNetworkTools] POST:ZZCURL_API_PERSONAL parameters:param finished:^(id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            ZZCLog(@"失败-%@",error);
        }else {
            NSDictionary *X = responseObject;
            ZZCLog(@"-%@",responseObject);
            self.meInfoModel = [ZZCMeInfo mj_objectWithKeyValues:responseObject[@"data"]];
            [self.meTableView reloadData];
            NSUserDefaults *user =  [NSUserDefaults standardUserDefaults];
            [user setObject:X[@"data"][@"phone"] forKey:@"userphone"];
            [user setBool:[X[@"data"][@"isset_pay_password"] intValue] forKey:@"is_set_paypassward"];
            NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
//            [store setValue:X[@"data"][@"nickname"] forKey:@"NICK_NAME"];
            if ( [X[@"data"][@"is_company"] intValue] == 0 ) {
                NSLog(@"！！！！！个人帐号");
                [store setInteger:0 forKey:@"IS_COMPANY"];
            } else if([responseObject[@"data"][@"is_company"] intValue] == 1) {
                NSLog(@"！！！！！企业帐号");
                [store setInteger:1 forKey:@"IS_COMPANY"];
            }
            if ([X[@"code"] isEqual:@(301)]) {
                NSLog(@"账号已在别的设备登录");
                _WARN = responseObject[@"msg"];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"userWarning" object:nil];
                [self alertView];
            }
        }
    }];

}

//退出登录后刷新数据源
- (void)reloadLeaveData {
    self.isLogin = NO;
    [self.meTableView reloadData];
}
#pragma mark - 数据源方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
     return self.meData.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ZZCMeCell *cell = [tableView dequeueReusableCellWithIdentifier:meCell];
    cell.selectionStyle = NO;
    cell.titleLabel.text = self.meData[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (!_isLogin) {
        [self goBackLogin];
    } else {
        if (indexPath.row == 0) {
            // @"我的订单"
            ZZCMyOrderController *myOrder = [ZZCMyOrderController new];
            [self.navigationController pushViewController:myOrder animated:YES];
        
        }else if (indexPath.row == 1) {
            //@"我的资产"
            ZZCOwnPropertyController *own = [ZZCOwnPropertyController new];
            [self.navigationController pushViewController:own animated:YES];

        }else if (indexPath.row == 2) {
            // @"劳务合作"
            ZZCMyLabourController *mL = [ZZCMyLabourController new];
            [self.navigationController pushViewController:mL animated:YES];
            
        }else if (indexPath.row == 3) {
            // @"交易记录"
            ZZCTransactionRecordController *TR = [ZZCTransactionRecordController new];
            [self.navigationController pushViewController:TR animated:YES];

        }else if (indexPath.row == 4) {
            //@"需要资产"
            ZZCNeedAssetsController *Asset = [ZZCNeedAssetsController new];
            [self.navigationController pushViewController:Asset animated:YES];

        }else if (indexPath.row == 5) {
            // @"二维码"
            ZZCTwoDimensionalController *two = [ZZCTwoDimensionalController new];
            two.qrcode = self.meInfoModel.qrcode;
            [self.navigationController pushViewController:two animated:YES];

        }else if (indexPath.row == 6) {
            // @"设置"
            ZZCSetUpController *set = [ZZCSetUpController new];
            [self.navigationController pushViewController:set animated:YES];

        }
    }
}

//未登陆直接跳转登陆页面
- (void)goBackLogin {
    ZZCLoginController *LoginVC = [ZZCLoginController new];
    [self.navigationController pushViewController:LoginVC animated:YES];
}



- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    ZZCMeHeadView *headView = [ZZCMeHeadView meHeadView];
    [headView.loginBtn addTarget:self action:@selector(loginBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [headView.collectBtn addTarget:self action:@selector(collectBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [headView.recordBtn addTarget:self action:@selector(recordBtnClick) forControlEvents:UIControlEventTouchUpInside];
    //这里你判断是否登录的条件
    if (!self.isLogin) {
        headView.loginView.hidden = YES;
    }else {
        headView.loginBtn.hidden = YES;
        //如果登录，可以将属性赋值
        //比如
        headView.userNameLabel.text = self.meInfoModel.nickname;
        headView.userTypeLabel.text = self.meInfoModel.grade;
        headView.balanceLabel.text = [NSString stringWithFormat:@"%@U币",self.meInfoModel.money];
        headView.quotaLabel.text = [NSString stringWithFormat:@"%.2f",[self.meInfoModel.money_ed floatValue]];
        //头像
        NSURL *url = [NSURL URLWithString:self.meInfoModel.head_img];
        [headView.iconView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"未登录头像"]];
        headView.iconView.clipsToBounds = YES;
        //给login添加点击事件
        headView.iconView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(propertyInfo)];
        [headView.iconView addGestureRecognizer:tap];
    }
    return headView;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 146;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    return @"";
}
#pragma mark - 监听按钮点击事件
//登录按钮
- (void)loginBtnClick {
    ZZCLog(@"你点击了登录按钮");
    if (!_isLogin) {
        [self goBackLogin];
    } else {
        ZZCLoginController *login = [ZZCLoginController new];
        [self.navigationController pushViewController:login animated:YES];
    }
}
//我的收藏
- (void)collectBtnClick {
    ZZCLog(@"你点击了我的收藏按钮");
    if (!_isLogin) {
        [self goBackLogin];
    } else {
        ZZCCollectController *collect = [ZZCCollectController new];
        collect.title = @"我的收藏";
    [self.navigationController pushViewController:collect animated:YES];
    }
}
//浏览记录
- (void)recordBtnClick {
    ZZCLog(@"你点击了浏览记录按钮");
    if (!_isLogin) {
        [self goBackLogin];
    } else {
        ZZCRecordController *record = [ZZCRecordController new];
        record.title = @"浏览记录";
    [self.navigationController pushViewController:record animated:YES];
    }
}

//个人信息
- (void)propertyInfo {
    ZZCPropertyController *pro = [ZZCPropertyController new];
    pro.imgUrl = self.meInfoModel.head_img;
    pro.meInfoModel = self.meInfoModel;
    [self.navigationController pushViewController:pro animated:YES];
}
#pragma mark - 懒加载
- (UITableView *)meTableView {
    if (_meTableView == nil) {
        _meTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ZZCScreenW, ZZCScreenH-64) style:UITableViewStyleGrouped];
        [_meTableView registerNib:[UINib nibWithNibName:@"ZZCMeCell" bundle:nil] forCellReuseIdentifier:meCell];
        _meTableView.delegate = self;
        _meTableView.dataSource = self;
        _meTableView.separatorStyle = NO;
        _meTableView.showsVerticalScrollIndicator = NO;
        _meTableView.rowHeight = 44;
    }
    return _meTableView;
}
- (NSMutableArray *)meArray {
    if (_meArray == nil) {
        _meArray = [NSMutableArray array];
    }
    return _meArray;
}

- (NSArray *)meData {
    if (_meData == nil) {
        _meData = [NSArray array];
    }
    return _meData;
}

- (void)alertView
{
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:_WARN  message:@"请重新登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.alertViewStyle = UIAlertViewStyleDefault;
    [alert show];
}
//监听点击事件 代理方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *btnTitle = [alertView buttonTitleAtIndex:buttonIndex];
    if ([btnTitle isEqualToString:@"取消"]) {
        NSLog(@"你点击了取消");
    }else if ([btnTitle isEqualToString:@"确定"] ) {
        NSLog(@"你点击了确定");
        ZZCLoginController *login = [ZZCLoginController new];
        [self.navigationController pushViewController:login animated:YES];
        //        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    }//https在iTunes中找，这里的事件是前往手机端App store下载微信
}

@end
